

# 个人中心
from flask import jsonify, redirect, url_for, render_template, request, g, abort

from info import db
from info.constants import USER_COLLECTION_MAX_NEWS, QINIU_DOMIN_PREFIX, USER_FOLLOWED_MAX_COUNT
from info.models import UserCollection, Category, News
from info.modules.user import user_blu
from info.utils.common import user_login_data, file_upload
from info.utils.response_code import error_map, RET
from flask import jsonify, current_app

@user_blu.route('/user_info')
@user_login_data
def user_info():
    user =g.user

    if not user:
        return redirect(url_for('home.index'))

    return render_template('news/user.html', user=user.to_dict())


@user_blu.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    user = g.user

    if not user:
        return redirect(url_for('home.index'))

    if request.method == 'GET':
              return render_template('news/user_base_info.html', user=user.to_dict())

    # POST

    signature = request.json.get('signature')
    nick_name = request.json.get('nick_name')
    gender = request.json.get('gender')

    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


@user_blu.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    user = g.user

    if not user:
        return redirect(url_for('home.index'))

    if request.method =='GET':
        return render_template('news/user_pic_info.html', user=user.to_dict())

    # POST

    avatar_file = request.files.get('avatar')
    # avatar_file.save('pic.jpg')

    try:
        avatar_bytes = avatar_file.read()

        try:
            file_name = file_upload(avatar_bytes)
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg=error_map[RET.THIRDERR])

        user.avatar_url = file_name

        print('图片名字', file_name)

    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


@user_blu.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    user = g.user

    if not user:
        return redirect(url_for('home.index'))

    if request.method == 'GET':
        return current_app.send_static_file('user_pass_info.html')

    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')

    if not all([new_password, old_password]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if not user.check_password(old_password):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    user.password = new_password

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


@user_blu.route('/collection', methods=['GET', 'POST'])
@user_login_data
def collection():
    user = g.user

    p = request.args.get('p', 1)

    p = int(p)

    pn = user.collection_news.order_by(UserCollection.create_time.desc()).paginate(p,USER_COLLECTION_MAX_NEWS)

    data = {
        'news_list': [news.to_dict() for news in pn.items],
        'total_page': pn.pages,
        'cur_page': pn.page
    }

    return render_template('news/user_collection.html', data=data)


@user_blu.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    user = g.user

    if not user:
        return abort(403)

    categories = Category.query.filter(Category.id != 1).all()

    if request.method =='GET':
        return render_template('news/user_news_release.html', categories=categories)


    # 获取参数校验参数
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    content = request.form.get('content')
    img_file = request.files.get('index_image')


    # 生成一条新闻纪录
    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content

    # 上传图片
    img_bytes = img_file.read()
    file_name = file_upload(img_bytes)
    news.index_image_url = QINIU_DOMIN_PREFIX + file_name
    # 设置作者的id
    news.user_id = user.id
    news.source = '个人发布'
    news.status = 1

    # 添加到数据库
    db.session.add(news)
    # 返回json
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


@user_blu.route('/news_list', methods=['GET'])
@user_login_data
def news_list():
    user = g.user
    if not user:
        return abort(403)

    p = request.args.get('p', 1)

    p = int(p)

    print('这个',p)
    try:
        pn = user.news_list.order_by(News.create_time.desc()).paginate(p, USER_COLLECTION_MAX_NEWS)

    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    print('这个是pn', pn)
    data = {
        'news_list': [news.to_review_dict() for news in pn.items],
        'total_page': pn.pages,
        'cur_page': pn.page
    }
    print('这个是pn', news_list)

    return render_template('news/user_news_list.html', data=data)


@user_blu.route('/user_follow', methods=['GET'])
@user_login_data
def user_follow():
    user = g.user
    if not user:
        return abort(403)

    p = request.args.get('p', 1)

    try:
        p = int(p)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        pn = user.followed.paginate(p, USER_FOLLOWED_MAX_COUNT)

    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)

    data = {
        'author_list': [author.to_dict() for author in pn.items],
        'total_page': pn.pages,
        'cur_page': pn.page
    }

    return render_template('news/user_follow.html', data=data)
